package com.compty.paint.web.member;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.compty.core.framework.util.StringUtil;
import com.compty.core.struts2.BaseAction;
import com.compty.core.utils.CommonsUtil;
import com.compty.paint.domain.Advertisement;
import com.compty.paint.domain.AuditState;
import com.compty.paint.domain.ImageInfo;
import com.compty.paint.manager.AdvertisementManager;
import com.compty.paint.manager.AuditStateManager;
import com.compty.paint.manager.ImageInfoManager;
import com.compty.paint.util.Constants;
import com.compty.security.domain.User;

/**
 * @Todo:广告管理
 * @author: zhuqh
 * @CreateTime:2011-9-16 上午09:26:46
 */
public class AdvertisementAction   extends BaseAction<Advertisement>{

	private static final long serialVersionUID = -8177367674701073296L;
	
	private AdvertisementManager advertisementManager;
	private AuditStateManager auditStateManager;
	private ImageInfoManager imageInfoManager;
	
	// ====================================================
	private Advertisement advertisement;
	private Date startDate;
	private Date endDate;
	private String operateStr; // 1表示隐藏,2表示删除
	
	/**
	 *@Todo:添加advertise prepare
	 *@CreateTime:2011-9-16 下午03:51:41
	 * @return
	 */
	public String addPrepare(){
		
		this.advertisement = null;
		
		Map advertisementMap = Constants.advertisementMap;
		request.setAttribute("advertisementMap", advertisementMap);
		
		return "addPrepare";
	}
	
	/**
	 *@Todo:分页列出广告
	 *@CreateTime:2011-9-16 上午09:33:11
	 * @return
	 */
	public String list(){
		
		String channelID = request.getParameter("channelID");
		
	   Criteria criteria;
		  
        if (sort != null) {
            boolean isAsc = dir.equalsIgnoreCase("asc");
            criteria = advertisementManager.createCriteria(sort, isAsc);
        } else {
            criteria = advertisementManager.createCriteria();
        }
        
        criteria.addOrder(Order.desc("id"));
        
        User userInfo = (User) session.getAttribute(Constants.Userinfo);
        if(userInfo!= null && "0".equals(userInfo.getAdministratorFlag())){
        	  criteria = criteria.add(Restrictions.eq("entryPerson", userInfo));
        }
        
        if(startDate != null){
        	 criteria = criteria.add(Restrictions.ge("uploadTime", startDate));
        }
        
        if(endDate != null){
        	 criteria = criteria.add(Restrictions.lt("uploadTime", endDate));
        }

        if ((filterTxt != null) && (filterValue != null)&& (!filterTxt.equals("")) && (!filterValue.equals(""))) {
            criteria = criteria.add(Restrictions.like(filterTxt,
                        "%" + filterValue + "%"));
        }
        
        if( channelID != null && !"".equals(channelID) ){
        	 criteria = criteria.add(Restrictions.eq("channelID", channelID));
        }

        this.page = advertisementManager.pagedQuery(criteria, curPage, pageSize);
        
		Map advertisementMap = Constants.advertisementMap;
		request.setAttribute("advertisementMap", advertisementMap);
		request.setAttribute("channelID", channelID);
        
        return "list";
	}
	
	/**
	 *@Todo:保存广告
	 *@CreateTime:2011-9-16 上午09:44:34
	 * @return
	 */
	public String save(){
		
		if(advertisement != null){
			
			User userInfo = (User) session.getAttribute(Constants.Userinfo);
			advertisement.setEntryPerson(userInfo);
			advertisement.setModifyPerson(userInfo);
			
			advertisement.setUploadTime(Calendar.getInstance().getTime());
			advertisement.setModifyTime(Calendar.getInstance().getTime());
			
			if(Constants.Auto_Audit){
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Pass);
				advertisement.setAuditState(auditState);
			}else{
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Init);
				advertisement.setAuditState(auditState);
			}
			
			String picImage = request.getParameter("picImage");
			String imageFilePath = getImageUploadPath() +CommonsUtil.getPathSymbol() + picImage; //图片物理路径
			File file = new File(imageFilePath);
			ImageInfo imageInfo = saveImageToDB(file, picImage, "11",picImage,Constants.AdvertiseFlag);
			advertisement.setImageInfo(imageInfo);
			
			advertisementManager.save(advertisement);
		}
		
		return "saved";
	}
	
	/**
	 *@Todo:修改广告，显示详情
	 *@CreateTime:2011-9-16 上午09:45:12
	 * @return
	 */
	public String modifyPrepare(){
		
		if( advertisement != null){
			
			Integer id = advertisement.getId();
			this.advertisement = advertisementManager.get(id);
			
			Map advertisementMap = Constants.advertisementMap;
			request.setAttribute("advertisementMap", advertisementMap);
		}
		
		return "modifyPreare";
	}
	
	/**
	 *@Todo:修改广告
	 *@CreateTime:2011-9-16 上午09:49:33
	 * @return
	 */
	public String modify(){
		
		if( advertisement != null){
			
			Advertisement ad = advertisementManager.get(advertisement.getId());
			
			ImageInfo imageInfo2 = ad.getImageInfo();
			Long removeId = imageInfo2 == null ? null : imageInfo2.getId();
			
			User userInfo = (User) session.getAttribute(Constants.Userinfo);
			ad.setModifyPerson(userInfo);
			
			ad.setModifyTime(Calendar.getInstance().getTime());
			ad.setTitle(advertisement.getTitle());
			ad.setLinkAddress(advertisement.getLinkAddress());
			ad.setChannelID(advertisement.getChannelID());
			
			String picImage = request.getParameter("picImage");
			if(!StringUtil.isDigit(picImage)){
				String absoluteImageFilePath = getImageUploadPath()+CommonsUtil.getPathSymbol() + picImage; //图片物理路径
				File file = new File(absoluteImageFilePath);
				ImageInfo imageInfo = saveImageToDB(file, picImage, "11",picImage,Constants.AdvertiseFlag);
				ad.setImageInfo(imageInfo);
			}
			
			advertisementManager.save(ad);  //保存修改后的广告
			
			if(!StringUtil.isDigit(picImage)){
				imageInfoManager.deleteById(removeId);
			}
		}
		
		return "modified";
	}
	
	/**
	 *@Todo:修改状态
	 *@author:zhuqh
	 *@CreateTime:2011-6-9 上午10:19:17
	 */
	public String changeUploadState() {

		if (advertisement != null) {
			Integer id = advertisement.getId();
			this.advertisement = advertisementManager.get(id);

			if ("1".equals(operateStr)) {//隐藏
				advertisement.setModifyTime(Calendar.getInstance().getTime());
				advertisementManager.save(advertisement);
			} else if ("2".equals(operateStr)) { //删除
				advertisementManager.removeById(id);
			}
			else if("3".equals(operateStr)){
				AuditState auditState = auditStateManager.findUniqueBy("english_name", Constants.Audit_State_Pass);  //审核通过
				advertisement.setAuditState(auditState);
				advertisement.setModifyTime(Calendar.getInstance().getTime());
				advertisementManager.save(advertisement);
			}
			else if("4".equals(operateStr)){
				AuditState auditState = auditStateManager.findUniqueBy("english_name", Constants.Audit_State_Overrule);  //审核驳回
				advertisement.setAuditState(auditState);
				advertisement.setModifyTime(Calendar.getInstance().getTime());
				advertisementManager.save(advertisement);
			}
			else if("5".equals(operateStr)){//显示
				advertisement.setModifyTime(Calendar.getInstance().getTime());
				advertisementManager.save(advertisement);
			}
		}
		
		return "changeState";
	}

	/**
	 *@Todo:保存图片至DB
	 * @param file 图片文件
	 * @param originalName  图片原始名字
	 * @param sharpId 图片形状类型   表示广告图片
	 */
	public ImageInfo saveImageToDB(File file,String originalName,String sharpId,String newNameUploaded,String memo){
		ImageInfo imageInfo = buildImage(file,originalName,sharpId,newNameUploaded,memo);
    	imageInfoManager.save(imageInfo);
    	writeImg(imageInfo,Constants.AdvertiseFlag);
    	return imageInfo;
	}
	
	public Advertisement getAdvertisement() {
		return advertisement;
	}

	public void setAdvertisement(Advertisement advertisement) {
		this.advertisement = advertisement;
	}

	public void setAdvertisementManager(AdvertisementManager advertisementManager) {
		this.advertisementManager = advertisementManager;
	}

	public void setAuditStateManager(AuditStateManager auditStateManager) {
		this.auditStateManager = auditStateManager;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public void setImageInfoManager(ImageInfoManager imageInfoManager) {
		this.imageInfoManager = imageInfoManager;
	}

	public String getOperateStr() {
		return operateStr;
	}

	public void setOperateStr(String operateStr) {
		this.operateStr = operateStr;
	}
}
